# 读取补全参数
import io
from typing import List
from io import BytesIO

import pandas as pd
import requests
from minio import S3Error
from seaman.core import JsonUtil

from common.client import client
from common.method import save
from common.model import BaseData, CompletionData, InterpolationData
from service.CompletionService import Completion
from service.InterpolationService import Interpolation
from common.custom import JAVA_URL
# 根据井信息读取基础数据
def read_base_data(wellId: str) -> List[BaseData]:
    # 假期测试服务器
    # url = JAVA_URL + "/well/" + wellId + "/survey/latest"

    url = "http://10.105.10.193:8080/well/" + wellId + "/survey/latest"

    # url = "http://localhost:8080/well/"+ wellId + "/survey/latest"
    response = requests.get(url)
    print(response)
    bucket_name: str
    object_name: str
    # 检查响应状态码
    if response.status_code == 200:
        # 获取返回的内容
        data = response.json()  # 如果返回的是 JSON 数据
        print(data)
        # 或者使用 response.text 获取原始文本内容
        bucket_name = data.get('bucketName')
        object_name = data.get('objectName')
        # 指定固定 @TODO 需要删除
        # bucket_name = 'well'
        # object_name = ''
        print('井{}测井记录存在{} {}'.format(wellId, bucket_name, object_name))
        file_data = client.get_object(bucket_name, object_name)
        df = pd.read_excel(BytesIO(file_data.read()))
        data_list: List[BaseData] = []
        for index, row in df.iterrows():
            item: BaseData = BaseData()
            # item.depth = row['depth']
            # item.inclination = row['inclination']
            # item.azimuth = row['azimuth']
            item.depth = row.iloc[0]
            item.inclination = row.iloc[1]
            item.azimuth = row.iloc[2]
            if index.__eq__(0):
                item.north = 0.0
                item.east = 0.0
                item.true_vertical_depth = item.depth
            data_list.append(item)
        # 井脏数据处理
        start_idx = 0
        # while (data_list[start_idx].azimuth == 0.0 and data_list[start_idx].inclination == 0.0) or (data_list[start_idx].azimuth < -9999 and data_list[start_idx].inclination < -9999):
        #     start_idx = start_idx + 1
        # end_idx = len(data_list) - 1
        # while (data_list[end_idx].azimuth == 0.0 and data_list[end_idx].inclination == 0.0) or (data_list[end_idx].azimuth < -9999 and data_list[end_idx].inclination < -9999):
        #     end_idx = end_idx - 1
        while data_list[start_idx].azimuth < -9999 and data_list[start_idx].inclination < -9999:
            start_idx = start_idx + 1
        end_idx = len(data_list) - 1
        while data_list[end_idx].azimuth < -9999 and data_list[end_idx].inclination < -9999:
            end_idx = end_idx - 1
        # 截取
        data_list = data_list[start_idx:end_idx+1]
        #如果没有 0  左侧插入 0 0 0
        if data_list[0].depth > 0.0:
            item: BaseData = BaseData()
            item.depth = 0.0
            item.inclination = 0.0
            item.azimuth = 0.0
            data_list.insert(0, item)
        return data_list
        # print(data)
    else:
        print('井{}对应测井记录不存在'.format(wellId))
        # 抛出异常
        raise FileNotFoundError

# 根据井信息，读取补全数据
def read_completion_data(wellId: str) -> List[CompletionData]:
    try:
        file_data = client.get_object("well", wellId + '/completion.xlsx')
        df = pd.read_excel(io.BytesIO(file_data.read()))
        data_list: List[CompletionData] = []
        for index, row in df.iterrows():
            item: CompletionData = CompletionData(None)
            item.depth = row['depth']
            item.inclination = row['inclination']
            item.azimuth = row['azimuth']
            item.north = row['north']
            item.east = row['east']
            item.true_vertical_depth = row['true_vertical_depth']
            item.full_angle = row['full_angle']
            data_list.append(item)
        return data_list
    except S3Error:
        completion = Completion(read_base_data(wellId))
        _list_: List[CompletionData] = completion.execute()
        # 写入补全信息
        save("well", wellId + '/completion.xlsx', _list_)
        return _list_


# 读取插值数据
def read_interpolation_data(wellId: str, space: float, is_slanting_point: bool) -> List[InterpolationData]:
    try:
        file_data = client.get_object("well", wellId + '/interpolation-' + space.__str__()+'.xlsx')
        df = pd.read_excel(io.BytesIO(file_data.read()))
        data_list: List[InterpolationData] = []
        for index, row in df.iterrows():
            item: InterpolationData = InterpolationData(None)
            item.depth = row['depth']
            item.inclination = row['inclination']
            item.azimuth = row['azimuth']
            item.north = row['north']
            item.east = row['east']
            item.true_vertical_depth = row['true_vertical_depth']
            item.full_angle = row['full_angle']
            item.curvature_radius = row['curvature_radius']
            item.arc_angle = row['arc_angle']
            item.dog_leg_severity = row['dog_leg_severity']
            item.face_angle = row['face_angle']
            item.inclination_rate = row['inclination_rate']
            item.azimuth_rate = row['azimuth_rate']
            data_list.append(item)
        return data_list
    except S3Error:
        print("存储中无插值数据")
        data_list: List[BaseData] = read_base_data(wellId)
        completion = Completion(data_list)
        _list_: List[CompletionData] = completion.execute()
        interpolation = Interpolation(_list_, space)
        # @TODO 此处执行数据筛选 , 可以修改为 2 * space
        interpolation.filter(space * 2, is_slanting_point)
        inter_list: List[InterpolationData] = interpolation.execute()
        # 存储为 Excel
        save("well", wellId + '/interpolation-' + space.__str__() + '.xlsx', inter_list)

        return inter_list



# if __name__ == '__main__':
#     # url = "http://localhost:8080/well/营170X/survey/latest"
#     # response = requests.get(url)
#     #
#     # # 检查响应状态码
#     # if response.status_code == 200:
#     #     # 获取返回的内容
#     #     data = response.json()  # 如果返回的是 JSON 数据
#     #     # 或者使用 response.text 获取原始文本内容
#     #     print(data)
#     # list = read_base_data('营170X')
#     list = read_completion_data('营170X')
#     # list = read_interpolation_data('z-18', 1.0)
#     # for item in list:
#     #     print(JsonUtil.obj2str(item))

